package tools.ensembl;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;

import tools.blat.EstAlignment;

public class EnsemblUtils {

	static String sep="\t";
	
	public static void main(String[] args)throws Exception{
		if(args.length>0){
			if(args[0].equals("genomicCluster")&&args.length==3){
				genomicCluster(args[1],args[2]);
			}else if(args[0].equals("splitFile")&&args.length==0){
				//Another method
			}else{
				System.err.println(printHelp());
				System.exit(616);
			}
		}else{
			System.err.println(printHelp());
			System.exit(616);
		}
		
		
	}
	
	public static String printHelp(){
		String help="EnsemblUtils manipulates files exported from the BioMart at the Ensembl web page\n";
		help+="Usage: ensemblUtils <cmd> <input>\n";
		help+="genomicCluster - Clusters an embossFile (ID\\tStart\\tEnd\\tChrom) without regard to strand on single nucleotide overlap. Returns a list of which cluster the transcripts belong to. The clusters are named prefix_Chrom_number. The number is running with 1 at the beginning of the chromosome.\n";
		help+="\t<input> = <ensembl file> <prefix>\n";
		
		return help;
	}
	
	public static void genomicCluster(String ensemblFile,String prefix)throws Exception{
		HashMap<String, ArrayList<EstAlignment>> map= new HashMap<String, ArrayList<EstAlignment>>();
		BufferedReader in= new BufferedReader(new FileReader(ensemblFile));
//		in.readLine(); //read the headers away...
		EstAlignment ea;
		String[] l;
		ArrayList<EstAlignment> tmpEA;
		for(String s=in.readLine();s!=null;s=in.readLine()){
			l=s.split("\t");
			if(l.length>3){
				ea=genomicCluster_line2ea(l);
				if(map.containsKey(ea.tname)){
					map.get(ea.tname).add(genomicCluster_findPos(map.get(ea.tname),ea), ea);
				}else{
					tmpEA= new ArrayList<EstAlignment>();
					tmpEA.add(ea);
					map.put(ea.tname, tmpEA);
				}
			}
		}
		//print
		for(String key : map.keySet()){
			tmpEA=map.get(key);
			int nr=0,end=0;
			for (EstAlignment ref : tmpEA) {
				if(ref.tstart<end){
					end=ref.tend>end?ref.tend:end;
				}else{
					nr++;
					end=ref.tend;
				}
				System.out.println(prefix+"_"+ref.tname.replaceAll("_", "").replaceAll(" ", "")+"_"+nr+sep+prefix+sep+ref.tname.replaceAll("_", "").replaceAll(" ", "")+sep+nr+sep+ref.qname);
			}
		}
	}
	
	private static int genomicCluster_findPos(ArrayList<EstAlignment> tmpEA,EstAlignment ea){
		int i=0;
		EstAlignment ref;
		for(;i<tmpEA.size();i++){
			ref=tmpEA.get(i);
			if(ea.tstart<ref.tstart){
				return i;
			}else if(ea.tstart==ref.tstart){
				if(ea.tend<=ref.tend){
					return i;
				}
			}
		}
		return tmpEA.size();
	}
	
	private static EstAlignment genomicCluster_line2ea(String[] l)throws Exception{
		EstAlignment ea= new EstAlignment();
		ea.qname=l[0];
		ea.tstart=Integer.parseInt(l[1]);
		ea.tend=Integer.parseInt(l[2]);
		ea.tname=l[3];
		return ea;
	}
}
